package com.fanyouzhao.ehome.web.servlet;

import com.fanyouzhao.ehome.entity.User;
import com.fanyouzhao.ehome.service.UserService;
import com.fanyouzhao.ehome.service.impl.UserServiceImpl;
import org.apache.poi.hssf.usermodel.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet(name = "userExportServlet", urlPatterns = "/userExport")
public class userExportServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String fileName = "用户列表.xls";
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("用户列表");
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");

        String[] headers = {"序号", "ID","姓名", "手机号", "出生日期", "性别", "注册时间"};
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<User> all = null;
        try {
            all = userService.selectAll();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //建sheet表，赋值表头
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 添加数据行:
        int rowNum = 1;
        for (User item : all) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue(item.getId());
            dataRow.createCell(2).setCellValue(item.getName());
            dataRow.createCell(3).setCellValue(item.getPhone());
            dataRow.createCell(4).setCellValue(dateFormat.format(item.getBirth()));
            dataRow.createCell(5).setCellValue(item.getSex());
            dataRow.createCell(6).setCellValue(dateFormat.format(item.getRegTime()));
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
